package com.codehelper.freemarker;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.codehelper.TemplateFileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenarateForDDD {
    public static void main(String[] args) {
        /*运行前请按绿色注释的步骤根据实际情况修改相关信息*/

        /**==设置使用的模板目录===*/
        String templatePath = "/templates/ddd";

        /**==设置数据库连接信息===*/
        String jdbcUrl = "jdbc:mysql://192.168.110.164:3306/dongxiang?characterEncoding=utf8&serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true";
        String jdbcUsername = "dongxiang_test";
        String jdbcPwd = "dongxiang_123";

        /**==设置需要生成的表名==*/
        String tableName = "ns_account_label_t";

        Map<String, Object> customParams = new HashMap<>();

        /**== 根据需要配置是否生成各层==*/

        //是否需要生成application,默认生成
        customParams.put("need-Application", false);
        customParams.put("need-Proxy", true);
        customParams.put("need-Repository", true);
        //是否需要生成command controller，默认生成
        customParams.put("need-Api", false);
        customParams.put("need-CreateCommand", false);

        //是否需要在仓储相关类上生成按open_id查询方法，适用于有open_id字段且open_id为唯一值的场景
        customParams.put("generate_query_by_openid",true);

        //实体是否是聚合，如果是，则基于Aggregate规则生成仓储及实体类，否则，基于Entity生成
        boolean entity_aggregate_model=false;
        customParams.put("entity_aggregate",entity_aggregate_model);

        //是否生成查询接口相关类
        customParams.put("need-Views", false);



        /**==设置根包名==*/
        String rootPackage = "com.askj.vip.account";

        /**设置各种类型文件的子包名*/
        String entityPackage = rootPackage + "." + "infrastructure.po";
        String mapperPackage = rootPackage + "." + "infrastructure.mapper";
        String proxyPackage = rootPackage + "." + "infrastructure.proxy";
        String repositoryPackage = rootPackage + "." + "domain.repository";
        String repositoryImplPackage = rootPackage + "." + "infrastructure";
        String domainPackage = rootPackage + "." + "domain.model";
        String commandPackage = rootPackage + "." + "application.command";
        String applicationPackage = rootPackage + "." + "application";
        String controllerPackage = rootPackage + "." + "interfaces";

        String viewRootPackage=rootPackage+".representation";
        String viewConditionPackage=viewRootPackage+".query";
        String viewAppImplPackage=viewRootPackage+".infrastructure";

        customParams.put("ViewRootPackage", viewRootPackage);

        //设置各种文件代码生成的根目录
        String dir = "D:\\gitcodes\\ds-modules\\ds-vip\\ds-vip-core\\src\\main\\java";

        List<TemplateFileInfo> templateFileInfos = new ArrayList<>();
        templateFileInfos.add( TemplateFileInfo.javaFile("PO", entityPackage, joinPath(dir, entityPackage),"{entity}"));
        templateFileInfos.add( TemplateFileInfo.javaFile("Entity", domainPackage, joinPath(dir, domainPackage),"{entity}"+(entity_aggregate_model?"Aggregate":"")));
        templateFileInfos.add( TemplateFileInfo.javaFile("Mapper", mapperPackage, joinPath(dir, mapperPackage),"{entity}Mapper"));
        templateFileInfos.add( TemplateFileInfo.javaFile("Repository", repositoryPackage, joinPath(dir, repositoryPackage),"{entity}Repository"));
        templateFileInfos.add( TemplateFileInfo.javaFile("DefaultRepository", repositoryImplPackage, joinPath(dir, repositoryImplPackage),"Default{entity}Repository"));
        templateFileInfos.add( TemplateFileInfo.javaFile("Proxy", proxyPackage, joinPath(dir, proxyPackage),"{entity}Proxy"));
        templateFileInfos.add( TemplateFileInfo.javaFile("CreateCommand", commandPackage, joinPath(dir, commandPackage),"Create{entity}Command"));
        templateFileInfos.add( TemplateFileInfo.javaFile("Application", applicationPackage, joinPath(dir, applicationPackage),"{entity}Application"));
        templateFileInfos.add( TemplateFileInfo.javaFile("Api", controllerPackage, joinPath(dir, controllerPackage),"{entity}Api"));

        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_Api", viewRootPackage, joinPath(dir, viewRootPackage),"{entity}RepresentationApi"));
        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_ListView", viewRootPackage, joinPath(dir, viewRootPackage),"{entity}View"));
        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_DetailView", viewRootPackage, joinPath(dir, viewRootPackage),"{entity}DetailView"));
        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_QueryCondition", viewConditionPackage, joinPath(dir, viewConditionPackage),"{entity}Condition"));
        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_App", viewRootPackage, joinPath(dir, viewRootPackage),"{entity}Representation"));
        templateFileInfos.add( TemplateFileInfo.javaFile("VIEWS_AppImpl", viewAppImplPackage, joinPath(dir, viewAppImplPackage),"Default{entity}Representation"));


        FastAutoGenerator.create(new DataSourceConfig.Builder(jdbcUrl, jdbcUsername, jdbcPwd))
                .globalConfig(builder -> {
                    builder.author("xieqiang") // 设置类上的作者注释
                            .disableOpenDir()
                            .fileOverride() // 覆盖已生成文件
                            .dateType(DateType.TIME_PACK);
                })
                .strategyConfig(builder -> {
                    builder.addInclude(tableName) // 设置需要生成的表名
                            /**==设置过滤表前缀==*/
                            .addTablePrefix("ns_", "as_", "sys_").addTableSuffix("_t");
                })
                .injectionConfig(consumer -> {
                    Map<String, String> customFile = new HashMap<>();
                    // 设置模板
                    File[] templates = new File(GenarateForDDD.class.getResource(templatePath).getFile()).listFiles();
                    for (File template : templates) {
                        customFile.put(template.getName().substring(0, template.getName().indexOf(".")), templatePath + "/" + template.getName());
                    }
                    consumer.customFile(customFile);
                    consumer.customMap(customParams);

                })
                .templateEngine(
                        new CustomFreemarkerTemplateEngine(templateFileInfos))
                .execute();
    }

    private static String joinPath(String parentDir, String packageName) {
        if (StringUtils.isBlank(parentDir)) {
            parentDir = System.getProperty("java.io.tmpdir");
        }

        if (!StringUtils.endsWith(parentDir, File.separator)) {
            parentDir = parentDir + File.separator;
        }

        packageName = packageName.replaceAll("\\.", "\\" + File.separator);
        return parentDir + packageName;
    }
}